import ctypes
import time
import psutil
import sys

# ---------------------------
# 1. IsDebuggerPresent 检测
# ---------------------------
def is_debugger_present():
    return ctypes.windll.kernel32.IsDebuggerPresent() != 0

# ---------------------------
# 2. PEB.BeingDebugged 检测
# ---------------------------
class PROCESS_BASIC_INFORMATION_STRUCT(ctypes.Structure):
    _fields_ = [
        ("Reserved1", ctypes.c_void_p),
        ("PebBaseAddress", ctypes.c_void_p),
        ("Reserved2", ctypes.c_void_p * 2),
        ("UniqueProcessId", ctypes.c_void_p),
        ("Reserved3", ctypes.c_void_p)
    ]

def is_being_debugged_peb():
    h_process = ctypes.windll.kernel32.GetCurrentProcess()
    pbi = PROCESS_BASIC_INFORMATION_STRUCT()
    return_length = ctypes.c_ulong()

    status = ctypes.windll.ntdll.NtQueryInformationProcess(
        h_process,
        0,
        ctypes.byref(pbi),
        ctypes.sizeof(pbi),
        ctypes.byref(return_length)
    )

    if status != 0:
        return False

    peb = ctypes.create_string_buffer(8)
    bytesRead = ctypes.c_size_t()

    if ctypes.windll.kernel32.ReadProcessMemory(
        h_process,
        pbi.PebBaseAddress,
        peb,
        8,
        ctypes.byref(bytesRead)
    ):
        return peb.raw[2] != 0
    return False

# ---------------------------
# 3. INT3/异常检测
# ---------------------------
def detect_int3_debugger():
    try:
        ctypes.string_at(0)  # 引发异常
        return True
    except:
        return False

# ---------------------------
# 4. 父进程名称检测
# ---------------------------
def get_parent_process_name():
    parent = psutil.Process().parent()
    return parent.name() if parent else ""

def is_launched_by_debugger():
    suspicious_parents = ["ollydbg", "x64dbg", "ida", "windbg", "processhacker"]
    pname = get_parent_process_name().lower()
    return any(s in pname for s in suspicious_parents)

# ---------------------------
# 5. 时间延迟检测
# ---------------------------
def check_time_drift():
    start = time.perf_counter()
    time.sleep(0.1)
    duration = time.perf_counter() - start
    return duration > 0.3

# ---------------------------
# 综合反调试函数
# ---------------------------
def anti_debug_checks():
    print("[*] 开始进行反调试检测...")

    if is_debugger_present():
        print("[!] 检测到调试器附加 (IsDebuggerPresent)，退出")
        sys.exit(1)

    if is_being_debugged_peb():
        print("[!] 检测到调试标志 (PEB.BeingDebugged)，退出")
        sys.exit(1)

    if detect_int3_debugger():
        print("[!] 异常未抛出，可能被调试器拦截，退出")
        sys.exit(1)

    if is_launched_by_debugger():
        print("[!] 父进程疑似调试器，退出")
        sys.exit(1)

    if check_time_drift():
        print("[!] 时间延迟异常，疑似调试器，退出")
        sys.exit(1)

    print("[+] 反调试检测通过，继续运行")

# ---------------------------
# 主程序入口
# ---------------------------
if __name__ == "__main__":
    anti_debug_checks()
    print("Hello, World!")
